#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# this lesson is based on python 3
# 线程(Thread)是最小的执行单元，而进程(Process)由至少一个线程组成。
# 如何调度进程和线程，完全由操作系统决定，程序自己不能决定什么时候执行，执行多长时间。

# ===MULTIPROCESSING===

from multiprocessing import Process, Pool, Queue
import os, time, random

# 子进程要执行的代码
def run_proc(name):
    print('Run child process %s (%s)...' % (name, os.getpid())) # os get process id

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Process(target=run_proc, args=('test',)) # name of process and parameters
    print('Child process will start.')
    p.start() # .start start the process
    p.join() # .join wait for the end of the process then continue
    print('Child process end.')

# 如果要启动大量的子进程，可以用进程池的方式批量创建子进程：
def long_time_task(name):
    print('Run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('Task %s runs %0.2f seconds.' % (name, (end - start)))

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Pool(4) # 最多同时执行4个进程, 默认大小是CPU的核数
    for i in range(5):
        p.apply_async(long_time_task, args=(i,))
    print('Waiting for all subprocesses done...')
    p.close() # 调用join()之前必须先调用close()，调用close()之后就不能继续添加新的Process了
    p.join() # 对Pool对象调用join()方法会等待所有子进程执行完毕
    print('All subprocesses done.')

# 启动一个子进程，然后控制其输入和输出:
import subprocess

print('$ nslookup www.python.org')
r = subprocess.call(['nslookup', 'www.python.org']) # == run 'nslookup www.python.org' in cmd
print('Exit code:', r)

print('$ nslookup')
p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = p.communicate(b'set q=mx\npython.org\nexit\n')
# .communicate interact with process: Send data to stdin and close it. 
# Read data from stdout and stderr, until end-of-file is reached.
'''
set q=mx
python.org
exit
'''
print(output.decode('utf-8'))
print('Exit code:', p.returncode)

# 通过Pipes和Queue实现进程间的通信
# 写数据进程执行的代码:
def write(q):
    print('Process to write: %s' % os.getpid())
    for value in ['A', 'B', 'C']:
        print('Put %s to queue...' % value)
        q.put(value) # put value to queue
        time.sleep(random.random())

# 读数据进程执行的代码:
def read(q):
    print('Process to read: %s' % os.getpid())
    while True:
        value = q.get(True) # keep getting True value from queue
        print('Get %s from queue.' % value)

if __name__=='__main__':
    # 父进程创建Queue，并传给各个子进程：
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    # 启动子进程pw，写入:
    pw.start()
    # 启动子进程pr，读取:
    pr.start()
    # 等待pw结束:
    pw.join()
    # pr进程里是死循环，无法等待其结束，只能强行终止:
    pr.terminate()

'''
=== Multithreading ===
'''
import threading

# 新线程执行的代码:
def loop():
    print('thread %s is running...' % threading.current_thread().name) # current_thread()永远返回当前线程的实例
    n = 0
    while n < 5:
        n = n + 1
        print('thread %s >>> %s' % (threading.current_thread().name, n))
        time.sleep(1)
    print('thread %s ended.' % threading.current_thread().name)

print('thread %s is running...' % threading.current_thread().name) # MainThread
t = threading.Thread(target=loop, name='LoopThread') # 把一个函数传入并创建Thread实例
t.start() # 然后调用start()开始执行
t.join()
print('thread %s ended.' % threading.current_thread().name)

# 多线程和多进程最大的不同在于，多进程中，同一个变量，各自有一份拷贝存在于每个进程中，互不影响，
# 而多线程中，所有变量都由所有线程共享，所以，任何一个变量都可以被任何一个线程修改，
# 因此，线程之间共享数据最大的危险在于多个线程同时改一个变量，把内容给改乱了。

# 假定这是你的银行存款:
balance = 0
lock = threading.Lock() # 创建一个Lock的实例

def change_it(n):
    # 先存后取，结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
    for i in range(100000):
        # 先要获取锁:
        lock.acquire() # 只有一个线程能成功地获取锁，然后继续执行代码
        try:
            # 放心地改吧:
            change_it(n)
        finally:
            # 改完了一定要释放锁:
            lock.release()

t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join() # 由于线程的调度是由操作系统决定的，当t1、t2交替执行时，只要循环次数足够多，balance的结果就不一定是0了。
print(balance)

'''
由于GIL锁的存在，Python不能利用多线程实现多核任务，但可以通过多进程实现多核任务。
'''

'''
 === ThreadLocal ===
'''

# 创建全局ThreadLocal对象:
local_school = threading.local()
# 虽然是全局变量，但每个线程都只能读写自己线程的独立副本，互不干扰。
# ThreadLocal解决了参数在一个线程中各个函数之间互相传递的问题。

def process_student():
    # 获取当前线程关联的student:
    std = local_school.student
    print('Hello, %s (in %s)' % (std, threading.current_thread().name))

def process_thread(name):
    # 绑定ThreadLocal的student:
    local_school.student = name
    process_student()

t1 = threading.Thread(target= process_thread, args=('Alice',), name='Thread-A')
t2 = threading.Thread(target= process_thread, args=('Bob',), name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()